package com.itheima.grow.job;

import com.alibaba.fastjson.JSONObject;
import com.itheima.grow.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;


/**
 * 每条给区域经理发邮件说你有多少个单子需要处理
 */
@Component
@Slf4j
public class AutoSentEmailManagerJob {

    @Autowired
    private RedissonClient redissonClient;

    @Scheduled(cron = "0 0 14 * * ? ")
    public void autoSentEmailManager(){
        System.out.println("fetch命令");
        log.info("dev2分支修改代码--->begin!");
        log.info("每天18:00给区域经理发邮件--->begin!");
        String key = this.getClass().getSimpleName() + ":" + DateUtil.formatDate(DateUtil.getCurrentTime(), DateUtil.FORMAT_5);
        RLock rLock = redissonClient.getLock(key);
        boolean tryLock = true;
        try {
            log.info("[给区域经理发邮件定时任务]获取分布式锁key：{}",key);
            tryLock = rLock.tryLock(0, 1, TimeUnit.MINUTES);
            log.info("[给区域经理发邮件定时任务]是否成功获取分布式锁：{}",tryLock);
            if(tryLock){
                System.out.println("===============================");
            }
        } catch (Exception e) {
            log.info("给区域经理发邮件失败原因:{}", JSONObject.toJSONString(e));
        }finally {
            if (tryLock && rLock.isHeldByCurrentThread()) {
                rLock.unlock();
                log.info("[给区域经理发邮件定时任务]释放分布式锁Key：{}",key);
            }
        }
        log.info("每天18:00给区域经理发邮件--->end!");
    }
}
